#include "UnitTest++.h"
#include "jpeglib.h"
#include <iostream>
using namespace std;

TEST (Jpeg_read)
{
	jpeg_decompress_struct cinfo;
    jpeg_error_mgr         jerr;

	FILE* fp = fopen("../res/test02.jpg", "rb");
	CHECK (fp != NULL);

    cinfo.err = jpeg_std_error (&jerr);
    jpeg_create_decompress (&cinfo);

    jpeg_stdio_src (&cinfo, fp);

    jpeg_read_header (&cinfo, true);
    jpeg_start_decompress (&cinfo);
  
    int width  = cinfo.output_width;
    int height = cinfo.output_height;
    int bpp    = cinfo.output_components;
	int format = cinfo.out_color_space;

    JSAMPARRAY rows   = new JSAMPROW [height];
    for (int y = 0; y < height; y++ ) {
		rows[y] = new JSAMPLE [width*bpp];
    }

    while (cinfo.output_scanline < cinfo.output_height) {
        jpeg_read_scanlines (&cinfo,
                             &rows[cinfo.output_scanline],
                             cinfo.output_height - cinfo.output_scanline);
    }

	CHECK_EQUAL (JCS_RGB, format);
	CHECK_EQUAL (64     , height);
	CHECK_EQUAL (64     , width);
	CHECK_EQUAL (bpp    , 3);

	CHECK_CLOSE (255, (int)rows[0][0+0], 1.f);
	CHECK_CLOSE (0  , (int)rows[0][0+1], 1.f);
	CHECK_CLOSE (0  , (int)rows[0][0+2], 1.f);

	CHECK_CLOSE (0  , (int)rows[0][63*3+0], 1.f);
	CHECK_CLOSE (0  , (int)rows[0][63*3+1], 1.f);
	CHECK_CLOSE (255, (int)rows[0][63*3+2], 1.f);

	CHECK_CLOSE (0  , (int)rows[63][0], 1.f);
	CHECK_CLOSE (255, (int)rows[63][1], 1.f);
	CHECK_CLOSE (0  , (int)rows[63][2], 1.f);
	
	CHECK_CLOSE (255, (int)rows[63][63*3+0], 1.f);
	CHECK_CLOSE (255, (int)rows[63][63*3+1], 1.f);
	CHECK_CLOSE (255, (int)rows[63][63*3+2], 1.f);
	
	for (int y = 0; y < height; y++) {
		delete[] rows[y];
	}
    delete[] rows;

	jpeg_finish_decompress (&cinfo);
    jpeg_destroy_decompress (&cinfo);

	fclose (fp);
}
